//
//  SubViewController.m
//  GIFShow
//
//  Created by lanou11air029 on 15/3/31.
//  Copyright (c) 2015年 CK. All rights reserved.
//

#import "SubViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <UIImageView-PlayGIF/UIImageView+PlayGIF.h>
#import "MYCommentModel.h"
#import <CommonCrypto/CommonCrypto.h>
#import "MySettingOptions.h"
#import "CustomButton.h"
#import "CommentCell.h"
#import <MRProgress/MRProgress.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import "GifDownload.h"
#import "GifModel.h"    
#import "InputAssiocalView.h"
#import "NSString+stampToStr.h"
#import "RepoterView.h"
typedef NS_ENUM(NSInteger, PageIndex) {
    PageIndexPreview = -1,
    PageIndexCurrent,
    PageIndexNext,
};
@interface SubViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
//
@property (nonatomic, strong) NSString    * movieStr;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) UIImage     * movieImage;
@property (nonatomic, strong) NSString    * datePop;
@property (nonatomic, strong) NSString    * content;
@property (nonatomic) CGSize movieSize;
//@property (nonatomic, strong) UIImage * preImage;
@property (nonatomic, strong) NSMutableArray * commentList;

//
@property (nonatomic, strong) UIScrollView * backgroundScrollView;

@property (nonatomic, strong) UIImageView  * userHeadIcon;
//用户名
@property (nonatomic, strong) UILabel      * userNameLabel;
// 视频创建日期
@property (nonatomic, strong) UILabel      * createDateLabel;
@property (nonatomic, strong) UIImageView  * mainImageView;
//内容
@property (nonatomic, strong) UILabel      * mainLabel;

// 评论
@property (nonatomic, strong) RepoterView * myShareView;

@property (nonatomic, strong) InputAssiocalView * commonView;
@end

@implementation SubViewController
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//    [self.moviePlayer play];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

-(void)dealloc{
    _tableView.delegate = nil;
}
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        [_tableView registerClass:[CommentCell class] forCellReuseIdentifier:@"comment"];
        
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.edgesForExtendedLayout = UIRectEdgeTop;
    self.automaticallyAdjustsScrollViewInsets = NO;

    self.backgroundScrollView.contentSize = CGSizeMake(self.view.bounds.size.width,self.view.bounds.size.height);
    self.backgroundScrollView.delegate = self;
    [self.view addSubview:self.backgroundScrollView];
    self.view.backgroundColor = [UIColor lightGrayColor];
    [UIView animateWithDuration:0.8 animations:^{
        self.view.backgroundColor=[UIColor whiteColor];
        
    }];
//    [self.navigationController.navigationBar setBackgroundColor:[UIColor yellowColor]];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"translucentBar"] forBarMetrics:UIBarMetricsCompact];
//    self.navigationController.navigationBar.shadowImage = [UIImage imageNamed:@"translucentBar"];
//    for (UIImageView * shadowImage in self.navigationController.navigationBar.subviews) {
//        shadowImage.hidden = YES;
//    }
//    self.navigationController.navigationBar.backgroundColor = [UIColor colorWithWhite:1 alpha:0.6];
//    [self.navigationController.navigationBar setBackgroundColor:];
//    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    [self setupSubviews];
    UIImage * backImage = [UIImage imageNamed:@"back_nav.png"];
    
    UIBarButtonItem * leftBackButton = [[UIBarButtonItem alloc]initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(didClickBackButton:)];

    
    self.navigationItem.leftBarButtonItem = leftBackButton;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
    self.navigationController.navigationBar.tintColor = [UIColor redColor];
    [self changepage:0];
    

//    // Do any additional setup after loading the view.
//    [self setupSubviews];
//    [self configGestures];
}

-(UIScrollView *)backgroundScrollView{
    if (_backgroundScrollView == nil) {
        _backgroundScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(1, 0, self.view.frame.size.width - 2, self.view.frame.size.height)];
        UIImageView * leftImageV = [[UIImageView alloc]initWithFrame:CGRectMake(-100, 100, 100, 90)];
        leftImageV.image = [UIImage imageNamed:@"prepage"];
        UIImageView * rightImageV = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width, 100, 100, 90)];
        rightImageV.image = [UIImage imageNamed:@"nextpage"];
        [_backgroundScrollView addSubview:leftImageV];
        [_backgroundScrollView addSubview:rightImageV];
        
//        _backgroundScrollView.backgroundColor 
    }
    return _backgroundScrollView;
}

-(UIImage *)getImageFromImage:(UIImage *)image{
    UIImage * renderImage =[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    CGRect backrect = CGRectMake(0, 0, 30, 30);
    UIGraphicsBeginImageContext(backrect.size);
    [renderImage drawInRect:backrect];
    UIImage * returnImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return returnImage;
}

-(void)setupSubviews{
    [self.backgroundScrollView addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    [UIView animateWithDuration:0.5 animations:^{
        self.tableView.backgroundColor = [UIColor whiteColor];
    }];
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [backButton setImage:[UIImage imageNamed:@"back_nav"] forState:UIControlStateNormal];
    backButton.frame = CGRectMake(17, 26, 30, 30);
    [self.view addSubview:backButton];
    [backButton addTarget:self action:@selector(didClickBackButton:) forControlEvents:UIControlEventTouchUpInside];
    if (self.gifModel) {
        self.commonView = [[InputAssiocalView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 35, self.view.frame.size.width, 35)];
        self.commonView.palceholderStr = @"请输入您的评论~~~";
        [self.view addSubview:self.commonView];
        [self.commonView addBackButtonTarget:self AndAction:@selector(wantback)];
        [self.commonView addSubmitButtonTarget:self AndAction:@selector(wantback)];
    }
}
// 评论返回
-(void)wantback{
    [self.navigationController popViewControllerAnimated:YES];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.commentList.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentCell * cell = [tableView dequeueReusableCellWithIdentifier:@"comment" forIndexPath:indexPath];
    MYCommentModel * commentItem = self.commentList[indexPath.row];
    cell.commentModel = commentItem;

    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat header = self.view.bounds.size.width * 0.1;
//    CGRect rect = CGRectMake(0, 0, self.view.frame.size.width-40, 1000);
//    NSDictionary * attribute = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14] forKey:NSFontAttributeName];
    MYCommentModel * commentModel = self.commentList[indexPath.row];
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 40, 100)];
    label.text = commentModel.content;
    label.font = [UIFont systemFontOfSize:14];
    label.numberOfLines = 0;
    [label sizeToFit];
    CGRect textRect = label.frame;
//    CGRect textRect = [commentModel.content boundingRectWithSize:rect.size options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil];
    return header + textRect.size.height +30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return self.movieSize.height+self.view.frame.size.width*0.27+30;
}


-(void)changepage:(PageIndex)page{
    [self.backgroundScrollView setContentOffset:CGPointMake(0, 0)];
    self.backgroundScrollView.userInteractionEnabled = NO;
    NSInteger index = 0;
    
    CGFloat movieWidth = 0;
    CGFloat movieHeight = 0;
    if (self.gifModel) {
        index = [self.myCollectionArray indexOfObject:self.gifModel];
        if (page+index<0|| page+index>=self.myCollectionArray.count) {
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        self.gifModel = [self.myCollectionArray objectAtIndex:(page+index)];
        self.movieStr = [self.gifModel.imagelist[0] valueForKey:@"thumb"];
        movieWidth = [[self.gifModel.imagelist[0] valueForKey:@"middle_w"] floatValue];
        movieHeight = [[self.gifModel.imagelist[0] valueForKey:@"middle_h"] floatValue];
        self.datePop = [NSString translateTimestamp:self.gifModel.created.floatValue];
        self.content = self.gifModel.content;

    }else if(self.gifDownload){
        index = [self.myCollectionArray indexOfObject:self.gifModel];
        if (page+index<0|| page+index>=self.myCollectionArray.count) {
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        self.gifDownload = [self.myCollectionArray objectAtIndex:(page+index)];
        self.movieStr = self.gifDownload.mainImageUrl;
        movieWidth = self.gifDownload.width.floatValue;
        movieHeight = self.gifDownload.height.floatValue;
        self.datePop = [NSString translateTimestamp:self.gifDownload.date.floatValue];
        self.content = self.gifDownload.content;
    }
 
    self.commentList = [[NSMutableArray alloc]init];
    for (NSDictionary * dic in self.gifModel.comment_list) {
        MYCommentModel * comment = [[MYCommentModel alloc]init];
        [comment setValuesForKeysWithDictionary:dic];
        [self.commentList addObject:comment];
    }
    
    movieHeight = self.view.frame.size.width / movieWidth * movieHeight;
    movieWidth = self.view.frame.size.width;
    self.movieStr = [self.movieStr stringByReplacingOccurrencesOfString:@"thumb" withString:@"large"];
    self.movieSize = CGSizeMake(movieWidth, movieHeight);
    [self.tableView reloadData];
    self.backgroundScrollView.userInteractionEnabled = YES;
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    view.clipsToBounds = YES;
    view.backgroundColor = [UIColor colorWithWhite:1 alpha:0.85];
    MySettingOptions * option = [MySettingOptions defaultOptions];
    if (self.gifModel) {
        //gif网址
        self.mainImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.movieSize.width, self.movieSize.height)];
    self.mainImageView.clipsToBounds = YES;
    self.mainImageView.contentMode = UIViewContentModeScaleAspectFill;
    MRProgressOverlayView * progressView = [MRProgressOverlayView showOverlayAddedTo:self.mainImageView title:@"努力加载中..." mode:MRProgressOverlayViewModeDeterminateHorizontalBar animated:YES];

    progressView.backgroundColor = [UIColor clearColor];
    [self.mainImageView sd_setImageWithURL:[NSURL URLWithString:self.movieStr] placeholderImage:self.movieImage options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        float rate = receivedSize*1.0 / expectedSize;
        if (rate>0 && rate<1) {
            [progressView setProgress:rate];
        }
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [MRProgressOverlayView dismissOverlayForView:self.mainImageView animated:YES];
    }];
    [view addSubview:self.mainImageView];
    }
    else if(self.gifDownload){
        NSString * filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSString * file = [filePath stringByAppendingPathComponent:self.gifDownload.art_id];
        NSData * data = [NSData dataWithContentsOfFile:file];
        self.mainImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.movieSize.width, self.movieSize.height)];
        self.mainImageView.gifData = data;
        [self.mainImageView startGIF];
        [view addSubview:self.mainImageView];
    }
    //用户头像
    CGRect contentViewBounds = self.mainImageView.frame;
    self.userHeadIcon = [[UIImageView alloc]initWithFrame:CGRectMake(contentViewBounds.size.width*0.05, contentViewBounds.origin.y+view.bounds.size.width*0.03+self.mainImageView.frame.size.height, contentViewBounds.size.width*0.13, contentViewBounds.size.width*0.13)];
    self.userHeadIcon.layer.cornerRadius = contentViewBounds.size.width*0.065;
    self.userHeadIcon.layer.masksToBounds = YES;
    self.userHeadIcon.layer.borderColor = [UIColor colorWithRed:0.7 green:0.8 blue:1 alpha:1].CGColor;
    self.userHeadIcon.layer.borderWidth = 1;
    
    [view addSubview:self.userHeadIcon];
    //用户名

    self.userNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.userHeadIcon.frame.origin.x+self.userHeadIcon.frame.size.width+view.frame.size.width*0.05, self.userHeadIcon.frame.origin.y, contentViewBounds.size.width * 0.7, 24)];
    self.userNameLabel.text = @"某人";
    if (self.gifDownload == nil) {
        NSDictionary * userinfo = self.gifModel.userinfo;
            [self.userHeadIcon sd_setImageWithURL:[NSURL URLWithString:[userinfo objectForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

        self.userNameLabel.text = [userinfo objectForKey:@"nickname"];
    }else{
        [self.userHeadIcon sd_setImageWithURL:[NSURL URLWithString:self.gifDownload.userHeadIconUrl] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        self.userNameLabel.text = self.gifDownload.username;
    }

    self.userNameLabel.font = [UIFont systemFontOfSize:option.userFontValue];
    [view addSubview:self.userNameLabel];
    
    // 视频创建日期
    self.createDateLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.userNameLabel.frame.origin.x, self.userNameLabel.frame.origin.y+self.userNameLabel.frame.size.height, self.userNameLabel.frame.size.width, self.userNameLabel.frame.size.height)];
    self.createDateLabel.font = [UIFont systemFontOfSize:option.otherFontValue];
    self.createDateLabel.textColor = [UIColor colorWithRed:0.8 green:0.6 blue:0.25 alpha:0.9];
    [view addSubview:self.createDateLabel];
    self.createDateLabel.text = self.datePop;

    //内容
    self.mainLabel = [[UILabel alloc]initWithFrame:CGRectMake(2, self.userHeadIcon.frame.origin.y+self.userHeadIcon.frame.size.height+5, view.bounds.size.width*0.9, 40)];
    self.mainLabel.font = [UIFont systemFontOfSize:option.userFontValue];
    [view addSubview:self.mainLabel];
    self.mainLabel.numberOfLines = 0;
    self.mainLabel.text = self.content;
    [self.mainLabel sizeToFit];

    
    self.myShareView = [[RepoterView alloc]initWithFrame:CGRectMake(0, self.mainLabel.frame.origin.y+self.mainLabel.frame.size.height, self.view.frame.size.width, self.view.frame.size.width*0.125)];
    [view addSubview:self.myShareView];
    

    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didClickViewResignTextField)];
    [view addGestureRecognizer:tap];

    return view;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor colorWithRed:0.7 green:0.9 blue:0.7 alpha:0.9];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        cell.contentView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.9 ];
    });
    [self didClickViewResignTextField];
//    UIViewController * vc = [[UIViewController alloc]init];
//    UIWebView * webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
//    [vc.view addSubview:webView];
//    NSURL * url = [NSURL URLWithString:@"http://gif.duowan.com/view/155822"];
//    [webView loadRequest:[NSURLRequest requestWithURL:url]];
//    UISwipeGestureRecognizer * swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:vc action:@selector(dismissViewControllerAnimated:completion:)];
//    [webView addGestureRecognizer:swipe];
//    [self presentViewController:vc animated:YES completion:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    MBProgressHUD * progress = nil;
    if (scrollView == self.backgroundScrollView) {
        if (scrollView.contentOffset.x >= 90) {
            progress = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            progress.mode = MBProgressHUDModeIndeterminate;
            progress.labelText = @"去往下一页";
            [self changepage:1];
            
        }else if(scrollView.contentOffset.x <= -90){
           progress = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            progress.mode = MBProgressHUDModeIndeterminate;
            progress.labelText = @"前往上一页";
            [self changepage:-1];
        }
        [progress hide:YES afterDelay:1];
    }
}

-(void)didClickBackButton:(UIBarButtonItem *)leftBarButton{

    [self.navigationController popViewControllerAnimated:YES];
}
-(void)didClickViewResignTextField{
    [self.commonView.inputView.contentTextField resignFirstResponder];
    [self.commonView.contentTextField resignFirstResponder];
    
    self.commonView.contentTextField.text = self.commonView.inputView.contentTextField.text;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
